package com.liit.controller.weixin.controller;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.liit.controller.weixin.process.ScanMsgProcess;
import com.liit.entity.OrgInfoFormMap;
import com.liit.entity.PartyAttendFormMap;
import com.liit.entity.PartyFormMap;
import com.liit.entity.PartySignFormMap;
import com.liit.exception.WeixinException;
import com.liit.mapper.PartyMapper;
import com.liit.plugin.PageView;
import com.liit.util.Common;
import com.liit.util.DictUtils;
import com.liit.util.IntegralUtils;
import com.liit.util.RegionUtils;

/**
 * 
 * @author dingweibo
 * @Title: UserPartyController.java
 * @Description: 用户活动
 * @date 2016年3月31日
 */
@Controller
@RequestMapping("/weixin/user/")
public class UserPartyController extends WeixinBaseController {

	@Resource
	PartyMapper mapper;

	@ResponseBody
	@RequestMapping("party/findByPage")
	public PageView findByPage(String pageNow, String pageSize, String type) throws Exception {
		PartyFormMap partyFormMap = new PartyFormMap();
		String openid = getOpenid();
		if ("pre".equals(type)) {
			partyFormMap.put("where", " id in (select partyId from t_party_attend where openid='" + openid
							+ "' union select partyId from t_party_sign where openid='" + openid + "') and status in (1,3)");
		} else if ("done".equals(type)) {
			partyFormMap.put("where", " id in (select partyId from t_party_attend where openid='" + openid + "') and status=4");
		} else {
			throw new WeixinException("参数异常");
		}
		partyFormMap = toFormMap(partyFormMap, pageNow, pageSize, " order by createTime desc ");
		List<PartyFormMap> partyList = mapper.findByPage(partyFormMap);
		Map<Integer, OrgInfoFormMap> temp = new HashMap<Integer, OrgInfoFormMap>();
		PartyAttendFormMap attendWhere = new PartyAttendFormMap();
		for (PartyFormMap p : partyList) {
			if (!temp.containsKey(p.getInt("orgInfoId"))) {
				temp.put(p.getInt("orgInfoId"), mapper.findbyFrist("id", p.get("orgInfoId").toString(), OrgInfoFormMap.class));
			}
			p.put("orgName", temp.get(p.getInt("orgInfoId")).getStr("orgName"));

			attendWhere.put("openid", openid);
			attendWhere.put("partyId", p.get("id"));
			
			//是否评价  进行中的活动不需要显示
			p.put("commentStatus", "pre".equals(type) ? "0" : mapper.findByNames(attendWhere).get(0).get("status"));
		}
		pageView.setRecords(partyList);
		return pageView;
	}

	@RequestMapping("party/comment")
	public String comment(Model model, Integer partyId) {
		model.addAttribute("party", mapper.findbyFrist("id", partyId.toString(), PartyFormMap.class));
		PartyAttendFormMap where = new PartyAttendFormMap();
		where.put("openid", getOpenid());
		where.put("partyId", partyId);
		List<PartyAttendFormMap> list = mapper.findByNames(where);
		if (CollectionUtils.isEmpty(list)) {
			throw new WeixinException("您未参与该活动,不允许评价");
		}
		model.addAttribute("partyAttend", list.get(0));
		return Common.BACKGROUND_PATH + "/weixin/user/comment";
	}

	@Transactional(readOnly = false)
	@RequestMapping("party/saveComment")
	public String saveComment(Integer partyId, RedirectAttributes redirectAttributes) {
		try {
			PartyAttendFormMap record = new PartyAttendFormMap();
			record.put("openid", getOpenid());
			record.put("partyId", partyId);
			List<PartyAttendFormMap> list = mapper.findByNames(record);
			if (CollectionUtils.isEmpty(list)) {
				throw new WeixinException("您未参与该活动,不允许评价");
			}
			record = list.get(0);
			if (record.getInt("status") == 1) {
				throw new WeixinException("您已评价该活动,请勿重复评价");
			}
			PartyAttendFormMap editEntity = getFormMap(PartyAttendFormMap.class);
			String startLevel = editEntity.get("starLevel").toString();
			if (!Common.isNumeric1(startLevel) || Integer.parseInt(startLevel) < 1) {
				throw new WeixinException("请选择星级评价");
			}
			editEntity.put("id", record.get("id"));
			editEntity.put("commentTime", new Timestamp(System.currentTimeMillis()));
			editEntity.put("status", 1);
			mapper.editEntity(editEntity);

			// 添加评价积分
			IntegralUtils.getInstance().partyComment(getOpenid(), partyId);

			return doMsg(null, null, null, getContextPath() + "/weixin/user/myparty.shtml", null, null, null, null, null, redirectAttributes);
		} catch (Exception e) {
			logger.error("评价异常", e);
			throw new WeixinException(e.getMessage());
		}
	}

	@RequestMapping("/party/detail")
	public String partyDetail(Model model) throws Exception {
		String partyId = getPara("partyId");
		PartyFormMap partyFormMap = new PartyFormMap();
		partyFormMap.put("id", partyId);
		List<PartyFormMap> result = mapper.findByNames(partyFormMap);
		if (result.size() > 0) {
			PartyFormMap record = result.get(0);
			record.put("province", RegionUtils.getRegionNameById(record.getStr("province")));
			record.put("city", RegionUtils.getRegionNameById(record.getStr("city")));
			record.put("area", RegionUtils.getRegionNameById(record.getStr("area")));
			record.put("street", RegionUtils.getRegionNameById(record.getStr("street")));
			record.put("type", DictUtils.getDictByValue("PARTY_TYPE", record.getInt("type")).get("label"));
			model.addAttribute(record);
		} else {
			throw new WeixinException("无此活动");
		}
		model.addAttribute("signs", mapper.findByAttribute("partyId", partyId, PartySignFormMap.class).size());
		
		// 使用jssdk
		HttpServletRequest request = getHttpServletRequest();
		useJSSDK(request.getRequestURL().toString() + (request.getQueryString() != null ? "?" + request.getQueryString() : ""));
				
		return Common.BACKGROUND_PATH + "/weixin/user/party_detail";
	}

	@ResponseBody
	@RequestMapping("party/listPartyByPage")
	public PageView listPartyByPage(String pageNow, String pageSize, String type) {
		PartyFormMap partyFormMap = new PartyFormMap();
		partyFormMap.put("where", " status in (1,3) ");
		if ("0".equals(type)) {
			partyFormMap.put("isRecommend", 0);
			partyFormMap.put("orderby", " order by createTime desc ");
			partyFormMap = toFormMap(partyFormMap, pageNow, pageSize, partyFormMap.getStr("orderby"));
		} else if ("1".equals(type)) {
			partyFormMap.put("isRecommend", 1);
			partyFormMap = toFormMap(partyFormMap, pageNow, pageSize, null);
		} else {
			throw new WeixinException("参数异常");
		}

		List<PartyFormMap> partyList = mapper.findByPage(partyFormMap);
		if (!CollectionUtils.isEmpty(partyList)) {
			for (PartyFormMap record : partyList) {
				record.put("area", RegionUtils.getRegionNameById(record.getStr("area")));
				record.put("street", RegionUtils.getRegionNameById(record.getStr("street")));
			}
		}
		pageView.setRecords(partyList);
		return pageView;
	}

	/**
	 * 活动报名详情
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("party/signParty")
	public String signParty(Model model) throws Exception {

		partyDetail(model);

		try {
			// 是否已报名活动
			PartySignFormMap partySign = new PartySignFormMap();
			partySign.put("partyId", getPara("partyId"));
			partySign.put("openid", getOpenid());
			model.addAttribute("isSignParty", !CollectionUtils.isEmpty(mapper.findByNames(partySign)));
		} catch (Exception e) {
			// 未关注时
			model.addAttribute("isSignParty", false);
		}

		model.addAttribute("now", System.currentTimeMillis() + (1000 * 60 * 60));// 当前时间加1小时
		model.addAttribute("signs", mapper.findByAttribute("partyId", getPara("partyId"), PartySignFormMap.class).size());
		
		// 使用jssdk
		HttpServletRequest request = getHttpServletRequest();
		useJSSDK(request.getRequestURL().toString() + (request.getQueryString() != null ? "?" + request.getQueryString() : ""));
		
		return Common.BACKGROUND_PATH + "/weixin/user/party_detail";
	}

	/**
	 * 活动报名
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("party/sign")
	public String sign(Model model, RedirectAttributes redirectAttributes) {
		
		if (StringUtils.isEmpty(getWeixinUserInfo().getStr("name"))) {
			return "redirect:/weixin/user/editMyinfo.shtml?type=0&partyId=" + getPara("partyId");
		}
		
		// 操作成功消息
		String successMsg = null;
		String icon = null;
		try {
			// 活动报名
			int retCode = ScanMsgProcess.scanEvent(getOpenid(), getPara("partyId"));
			if (retCode == Common.PARTY_MSG_TYPE_SIGN_SUCCESS) {
				successMsg = "活动报名成功";
			} else {
				successMsg = "活动报名失败";
				icon = "warn";
			}
		} catch (Exception e) {
			logger.error("活动报名失败", e);
			throw new WeixinException("活动报名失败");
		}

		// 使用jssdk
		useJSSDK("/weixin/weixinMsg.shtml");
		// 设置msg信息
		return doMsg(icon, successMsg, null, "javascript:wx.closeWindow();", null, null, null, null, null, redirectAttributes);
	}
}